package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Optional;


@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private IStrategyCommentRepository strategyCommentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveOrUpdate(StrategyComment strategyComment) {
        strategyCommentRepository.save(strategyComment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        Query query=new Query();
        //查询条件
        query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        //总数
        long count = mongoTemplate.count(query, StrategyComment.class);
        //排序
        Sort createTime = Sort.by(Sort.Direction.DESC, "createTime");
        //分页
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(createTime);
        query.with(pageRequest);
        //list
        List<StrategyComment> strategyComments = mongoTemplate.find(query, StrategyComment.class);
        return new PageImpl(strategyComments,pageRequest,count);
    }

    @Override
    public void thumbUp(String toid, Long userId) {
        Optional<StrategyComment> byId = strategyCommentRepository.findById(toid);
        StrategyComment strategyComment=null;
        if(byId.isPresent()) {
            strategyComment = byId.get();
        }
        List<Long> thumbuplist = strategyComment.getThumbuplist();
        if(thumbuplist.contains(userId)) {
            thumbuplist.remove(userId);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()-1);
        }else {
            thumbuplist.add(userId);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()+1);
        }
        strategyCommentRepository.save(strategyComment);
    }


}
